package de.gist.calldurationwatcher.preferences;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import de.gist.calldurationwatcher.R;
import de.gist.calldurationwatcher.helper.Utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.DialogPreference;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class PhoneListPreference extends DialogPreference {

	private String[] areaCodesValues;
	private ArrayList<String> savedAreaCodes;
	private Context ctx;
	private SharedPreferences preferences;
	private Spinner codesCombo;
	private ImageButton addCodeButton;
	private ListView areaCodesListView;
	private TextView areaCodeText;
	private static int minutesLeft;
	
	public PhoneListPreference(Context context, AttributeSet attrs) {
		super(context, attrs);

		preferences = PreferenceManager.getDefaultSharedPreferences(context);
		savedAreaCodes = new ArrayList<String>();
		
		ctx = context;
		areaCodesValues = context.getResources().getStringArray(R.array.areaCodesValues);
		
		String savedList = preferences.getString(context.getString(R.string.savedAreaCodes), null);
		
		List<String> list = null;
		if (savedList != null && savedList.trim().length() > 1)
			list = Arrays.asList(savedList.split(";"));
		
		if (list != null)
			savedAreaCodes = new ArrayList<String>(list);
		else
			savedAreaCodes = new ArrayList<String>();
		
		minutesLeft = preferences.getInt("minutesLeft", 0);
	}

	@Override
	protected View onCreateDialogView() {

		LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.phonelistpreferencelayout, null);
		
		try {
			
			areaCodeText = (TextView) view.findViewById(R.id.AreaCodeText);
			areaCodesListView = (ListView) view.findViewById(R.id.AreaCodesListView);
			addCodeButton = (ImageButton) view.findViewById(R.id.AddCodeButton);
			codesCombo = (Spinner) view.findViewById(R.id.AreaCodesCombo);
			ArrayAdapter<CharSequence> comboAdapter = ArrayAdapter.createFromResource(ctx, R.array.areaCodes, android.R.layout.simple_spinner_item);
			comboAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			codesCombo.setAdapter(comboAdapter);
			
			final ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(ctx, android.R.layout.simple_list_item_multiple_choice, savedAreaCodes);
			areaCodesListView.setAdapter(listAdapter);
			areaCodesListView.setChoiceMode(2);

			int codeIndex = preferences.getInt("selectedCountry", -1);
    		String[] codesArray = ctx.getResources().getStringArray(R.array.areaCodesValues);
    		String country = preferences.getString("countryPreference", null);
    		
    		int landCode = 0;
    		if (codeIndex != -1) {
	    		landCode = codeIndex;
    		} else if (country != null) {
    			for (int i = 0; i < codesArray.length; i++) {
    				if (codesArray[i].equals(country)) {
    					landCode = i;
    					break;
    				}
    			}
    		}
			if (landCode > -1)
				codesCombo.setSelection(landCode);
			
			
			addCodeButton.setOnClickListener(new View.OnClickListener() {
	            
				public void onClick(View v) {
					
					String code = areaCodeText.getText().toString();
					String landCode = areaCodesValues[codesCombo.getSelectedItemPosition()];
					int duration = 0;
					
					if (code.startsWith("+") || code.startsWith("00")) {
						code = code.replaceAll(" ", "");
						savedAreaCodes.add(code);
						duration = Utils.GetCallLogNumberDuration(ctx, code);
						duration += Utils.GetCallLogNumberDuration(ctx, "0" + code.replace('+', ' ').replaceAll("00" + landCode, "").replaceAll(" ", ""));
					}
					else {
						if (code.startsWith("0")) {
							code = "(+" + landCode + ") (0)" + code.substring(1).replaceAll(" ", "");
							savedAreaCodes.add(code);
						} else {
							code = "(+" + landCode + ") (0)" + code.replaceAll(" ", "");
							savedAreaCodes.add(code);
						}
						duration = Utils.GetCallLogNumberDuration(ctx, "0" + code.substring(code.lastIndexOf(')') + 1).replaceAll(" ", ""));
						duration += Utils.GetCallLogNumberDuration(ctx, "+" + landCode + code.substring(code.lastIndexOf(')') + 1).replaceAll(" ", ""));
					}
					
					minutesLeft = minutesLeft - duration;
					listAdapter.notifyDataSetChanged();
					areaCodeText.setText("");
	            }
	        });
			
			ImageButton removeCodesButton = (ImageButton) view.findViewById(R.id.removeAreaCodesButton);
			removeCodesButton.setOnClickListener(new View.OnClickListener() {
	            
				public void onClick(View v) {
					
					try {
						SparseBooleanArray checked = areaCodesListView.getCheckedItemPositions();
						if (checked == null)
							return;
						
						ArrayList<String> deleteValues = new ArrayList<String>();
						for (int i = 0; i < savedAreaCodes.size(); i++) {
							if (checked.get(i)) {
								deleteValues.add(savedAreaCodes.get(i));
							}
						}
						
						for (String item : deleteValues) {
							
							savedAreaCodes.remove(item);
							
							if (item.startsWith("(")) {
								String number = "0" + item.substring(item.lastIndexOf(")") + 1).replaceAll(" ", "");
								minutesLeft = minutesLeft + Utils.GetCallLogNumberDuration(ctx, number);
								
								number = item.substring(0, item.lastIndexOf("(")) + item.substring(item.lastIndexOf(")"));
								number = number.replace('(', ' ').replace(')', ' ').replaceAll(" ", "");
								minutesLeft = minutesLeft + Utils.GetCallLogNumberDuration(ctx, number);
							}
							minutesLeft = minutesLeft + Utils.GetCallLogNumberDuration(ctx, item);
						}
						listAdapter.notifyDataSetChanged();
						
					} catch (Exception ex) {
						Log.e("PhoneListPreference", ex.getMessage());
					}
	            }
	        });
			
		} catch (Exception ex) {
			
		}
		return view;
	}
	
	@Override
	protected void onDialogClosed(boolean positiveResult) {
	    super.onDialogClosed(positiveResult);

	    if (!positiveResult) {
	        return;
	    }
	    
	    if (shouldPersist()) {
	    	PersistDialogSettings();
	    }

	    notifyChanged();
	}

	private void PersistDialogSettings() {
		
		SharedPreferences.Editor editor = preferences.edit();
    	editor.putInt(ctx.getString(R.string.selectedCountry), codesCombo.getSelectedItemPosition());
    	editor.putString(ctx.getString(R.string.savedAreaCodes), Utils.JoinAreaCodes(savedAreaCodes));
    	editor.putInt("minutesLeft", minutesLeft);
    	editor.commit();
	}
}
